package com.lwj.filter;

import com.lwj.constant.ConstantDefinition;
import com.lwj.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LoginFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginFilter.class);

    /**
     * 保存不拦截的url
     */
    private static List<String> passUrls = new ArrayList<String>();

    /**
     * 上下文
     */
    private String ctxPath = null;

    /**
     * 重定向url
     */
    private static String redirectUrl = "/login.jsp";

    /**
     * 过滤器初始化方法
     *
     * @param filterConfig
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        String ignoreURL = filterConfig.getInitParameter("passURL");
        // 保存不拦截的url
        String[] ignoreURLArray = ignoreURL.split(",");
        for (String url : ignoreURLArray) {
            passUrls.add(url.trim());
        }
        ctxPath = filterConfig.getServletContext().getContextPath();
        System.out.println("ctx = " + ctxPath);
        LOGGER.info("不拦截的URL包括:");
        for (String url : passUrls) {
            LOGGER.info(url);
        }
    }

    /**
     * 过滤器方法
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String env = System.getProperties().getProperty("spring.profiles.active");
        // 请求的url
        String url = request.getRequestURI();
        // 相对路径
        String subUrl = url.substring(ctxPath.length());
        for (String urlStr : passUrls) {
            // 如果匹配, 则放行
            if (subUrl.indexOf(urlStr) > -1) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        AntPathMatcher antPathMatcher=new AntPathMatcher();
        if("dev".equals(env) && (antPathMatcher.match("/swagger-ui.html",subUrl) || antPathMatcher.match("/webjars/**",subUrl) ||
                antPathMatcher.match("/swagger-resources/**",subUrl) || antPathMatcher.match("/v2/api-docs",subUrl))){
            filterChain.doFilter(request, response);
            return;
        }
        //需要登录
        User user=(User) request.getSession().getAttribute(ConstantDefinition.SESSION_KEY_USERNAME);
        if(user==null){
            servletRequest.getRequestDispatcher("/login.jsp").forward(request,response);
        }else {
            filterChain.doFilter(request, response);
        }
    }

    public void destroy() {

    }

}
